package com.wenhai.spring.validation;

import org.springframework.context.MessageSource;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;

import java.util.Locale;

/**
 * {@link UserLoginValidator} 示例
 *
 * @author wenhai
 * @date 2020/10/15
 * @since OMP
 */
public class UserLoginValidatorDemo {

    public static void main(String[] args) {
        UserLogin userLogin = new UserLogin();
        userLogin.setPassword("11111");
        BeanPropertyBindingResult errors = new BeanPropertyBindingResult(userLogin, "user");
        ValidationUtils.invokeValidator(new UserLoginValidator(), userLogin, errors);
        MessageSource ms = createMessageSource();
        FieldError fieldError = errors.getFieldError();
        System.out.println("=========fieldError========");
        System.out.println(ms.getMessage(fieldError.getCode(), fieldError.getArguments(), Locale.getDefault()));

        for (ObjectError error : errors.getAllErrors()) {
            System.out.println(ms.getMessage(error.getCode(), error.getArguments(), Locale.getDefault()));
        }
    }

    private static MessageSource createMessageSource() {

        StaticMessageSource sms = new StaticMessageSource();
        sms.addMessage("field.required", Locale.getDefault(), "{0}不能为空");
        sms.addMessage("field.min.length", Locale.getDefault(), "字段{0}长度{1}小于最小长度{2}");

        return sms;
    }
}
